package com.css.dzj.dzjportal.modules.creditinfobase.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.aq.server.service.BaseService;
import com.css.dzj.dzjportal.common.util.R;
import com.css.dzj.dzjportal.common.util.excel.ExcelData;
import com.css.dzj.dzjportal.common.util.excel.ExportExcelUtils;
import com.css.dzj.dzjportal.common.util.http.HttpClientUtil;
import com.css.dzj.dzjportal.modules.creditinfobase.service.CreditInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/creditinfobase")
public class CreditInfoController {
    @Value("${ZFJG_URL}")
    private String zfjgUrl;
    @Autowired
    private CreditInfoService creditInfoService;
    @Autowired
    private BaseService baseService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 企业评估信息总数
     */
    @GetMapping("/gettotalnum")
    public R totalnum() {
        try {
            String result = HttpClientUtil.doGet(zfjgUrl + "/detail/export2");
            JSONArray jsonZfjgUnits = JSON.parseArray(result);
            if (jsonZfjgUnits == null) {
                return R.ok().put("data", 0);
            } else {
                return R.ok().put("data", jsonZfjgUnits.size());
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取信用监管list
     *
     * @param enterpriseName
     * @param enterpriseClassification
     * @param enterpriseScoreBegin
     * @param enterpriseScoreEnd
     * @param status
     */
    @GetMapping("/creditinfoList")
    public R creditinfoList(
            @RequestParam(name = "enterpriseName", required = false) String enterpriseName,
            @RequestParam(name = "enterpriseClassification", required = false) String enterpriseClassification,
            @RequestParam(name = "enterpriseScoreBegin", required = false) String enterpriseScoreBegin,
            @RequestParam(name = "enterpriseScoreEnd", required = false) String enterpriseScoreEnd,
            @RequestParam(name = "status", required = false) String status,
            @RequestParam Integer pageSize,
            @RequestParam Integer pageNo
    ) {
        try {
            HashMap params = new HashMap<String, Object>();
            params.put("enterpriseName", enterpriseName);
            params.put("enterpriseClassification", enterpriseClassification);
            params.put("enterpriseScoreBegin", enterpriseScoreBegin);
            params.put("enterpriseScoreEnd", enterpriseScoreEnd);
            params.put("status", status);
            params.put("pageSize", pageSize.toString());
            params.put("pageNo", pageNo.toString());
            String result = HttpClientUtil.doGet(zfjgUrl + "/detail/getPage", params);
            JSONObject data = JSON.parseObject(result);
            return R.ok().put("data", data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取企业信用评估信息详情
     */
    @GetMapping("/findCredit")
    public R findCredit(String enterpriseCreditCode) {
        try {
            String msg = HttpClientUtil.doGet(zfjgUrl + "/detail/queryById?enterpriseIdNumber="+enterpriseCreditCode);
            JSONObject jsonObject = JSON.parseObject(msg);
            if(jsonObject!=null&&jsonObject.get("code").equals(200)){
                return R.ok().put("data",jsonObject.get("data")).put("isClue",jsonObject.get("isClue"));
            }else {
                return R.error("查询失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取信用线索企业详情
     */
    @GetMapping("/findClue")
    public R findClue(String enterpriseIdNumber) {
        try {
            String msg = HttpClientUtil.doGet(zfjgUrl + "/clue/queryByIdNumber?enterpriseIdNumber="+enterpriseIdNumber);
            JSONObject jsonObject=(JSONObject)JSON.parse(msg);
            if(jsonObject!=null&&jsonObject.get("code").equals(200)){
                return R.ok().put("data",jsonObject.get("data")).put("isClue",jsonObject.get("isClue"));
            }else {
                return R.error("查询失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 根据ids导出企业信用评估信息
     *
     * @param ids
     */
    @GetMapping("/exportByIds")
    public R exportCreditAssessToExcel(HttpServletResponse response, @RequestParam String ids) {
        try {
            HashMap params = new HashMap<String, Object>();
            params.put("ids", ids);
            String result = HttpClientUtil.doGet(zfjgUrl + "/detail/exportByIds2", params);
            JSONArray jsonZfjgUnits = JSON.parseArray(result);
            // 导出
            export(jsonZfjgUnits, response);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 根据查询条件导出信用评估信息
     *
     * @param enterpriseName
     * @param enterpriseScoreBegin
     * @param  enterpriseScoreEnd
     * @param enterpriseClassification
     */
    @GetMapping("/export")
    public R export(HttpServletResponse response,
                    @RequestParam(required = false) String enterpriseName, @RequestParam(required = false) String enterpriseScoreBegin,
                    @RequestParam(required = false) String enterpriseScoreEnd, @RequestParam(required = false) String enterpriseClassification) {
        try {
            HashMap params = new HashMap<String, Object>();
            params.put("enterpriseName", enterpriseName);
            params.put("enterpriseScoreBegin", enterpriseScoreBegin);
            params.put("enterpriseScoreEnd",enterpriseScoreEnd);
            params.put("enterpriseClassification", enterpriseClassification);

            String result = HttpClientUtil.doGet(zfjgUrl + "/detail/export2", params);
            JSONArray jsonZfjgUnits = JSON.parseArray(result);
            export(jsonZfjgUnits, response);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 导出
     *
     * @param jsonZfjgUnits
     */
    public  void export(JSONArray jsonZfjgUnits, HttpServletResponse response) {
        // 创建导出实体
        ExcelData data = new ExcelData();
        data.setName("企业信用评估信息表");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("企业名称");
        titles.add("企业分类");
        titles.add("企业证件类型");
        titles.add("企业证件号码");
        titles.add("企业分数");
        titles.add("评估日期");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (int i = 0; i < jsonZfjgUnits.size(); i++) {
            ArrayList<Object> row = new ArrayList<>();
            Map<String, Object> eventMap = JSONObject.parseObject(jsonZfjgUnits.get(i).toString());
            row.add(eventMap.get("enterpriseName"));
            row.add(eventMap.get("enterpriseClassification"));
            row.add(eventMap.get("enterpriseIdType"));
            row.add(eventMap.get("enterpriseIdNumber"));
            row.add(eventMap.get("enterpriseScore"));
            row.add(eventMap.get("assessmentDate"));
            rows.add(row);
        }
        data.setRows(rows);
        try {
            // 导出
            ExportExcelUtils.exportExcel(request,response, "企业信用评估信息表.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
